package com.guet.service.impl;

import com.guet.DTO.PasswordEditDTO;
import com.guet.DTO.UserDTO;
import com.guet.VO.UserVO;
import com.guet.constant.UserConstant;
import com.guet.context.BaseContext;
import com.guet.exception.PasswordErrorException;
import com.guet.mapper.LoginMapper;
import com.guet.mapper.UserMapper;
import com.guet.service.UserService;
import org.apache.commons.codec.cli.Digest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LoginMapper loginMapper;


    /**
     * 获取用户基本信息
     *
     * @return
     */
    @Override
    public UserVO getUserInfo() {
        Long userId = BaseContext.getCurrentId();
        return userMapper.getUserInfo(userId);

    }

    /**
     * 修改用户信息
     *
     * @param userDTO
     */
    @Override
    public void update(UserDTO userDTO) {
        Long userId = BaseContext.getCurrentId();
        Map map = new HashMap();
        map.put("userId", userId);
        map.put("username", userDTO.getUsername());
        map.put("identify", userDTO.getIdentify());
        map.put("school", userDTO.getSchool());
        map.put("avatar", userDTO.getAvatar());
        userMapper.update(map);
    }

    /**
     * 更改用户密码
     *
     * @param passwordEditDTO
     */
    @Override
    public void updatePassword(PasswordEditDTO passwordEditDTO) {
        if (!passwordEditDTO.getNewPassword().equals(passwordEditDTO.getConfirmPassword())) {
            throw new PasswordErrorException("两次密码不一致");
        }
        if (!passwordEditDTO.getNewPassword().matches("^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,20}$")) {
            throw new PasswordErrorException("密码必须为8到20位，且包含字母和数字");
        }

        Long userId = BaseContext.getCurrentId();
        String password = loginMapper.queryPasswordById(userId);
        if (!password.equals(DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes()))) {
            throw new PasswordErrorException("密码错误");
        }
        String newPassword = DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes());
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("password", newPassword);
        userMapper.update(map);
    }
}
